package cn.trip.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.ibatis.annotations.Param;
import org.apache.log4j.Logger;
import org.apache.tomcat.util.bcel.Const;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;

import cn.trip.pojo.Safe_question;
import cn.trip.pojo.Trip_bill;
import cn.trip.pojo.Trip_question;
import cn.trip.pojo.Trip_tourist;
import cn.trip.pojo.Trip_user;
import cn.trip.service.user.UserService;
import cn.trip.utils.Constants;
import cn.trip.utils.PageSupport;

@Controller
@RequestMapping("/user")
public class UserController {

	Logger logger = Logger.getLogger(UserController.class);
	
	@Resource
	private UserService userService;
	
	
	@RequestMapping(value="login")
	public String login(){
		return "user/login";
	}
	
	@RequestMapping(value="dologin")
	public String dologin(Model model,@RequestParam(value="userCode",required=false)String userCode,
						@RequestParam(value="password",required=false)String password
						,HttpSession session){
		Trip_user user = userService.getUser(userCode, password);
		session.setAttribute(Constants.USER_SESSION,user);
		return "redirect:/user/dologinjudge";
	}
	
	@RequestMapping(value="/register")
	public String register(Model model){
		List<Trip_question> questions = userService.getAllQuestions();
		model.addAttribute("question",questions);
		return "user/register";
	}
	
	@RequestMapping(value="/registersuccess")
	public String registersave(@RequestParam(value="userName",required=false)String userName,
						@RequestParam(value="password",required=false)String password,
						@RequestParam(value="userEmail",required=false)String userEmail,
						@RequestParam(value="birth",required=false)String _birth,
						@RequestParam(value="userPhone",required=false)String userPhone,
						@RequestParam(value="userAddress",required=false)String userAddress,
						@RequestParam(value="sex",required=false)String _sex,
						@RequestParam(value="questionId",required=false)String _questionId,
						@RequestParam(value="answer",required=false)String answer,HttpSession session,Model model){
		logger.debug("userName=================>"+userName);
		logger.debug("password=================>"+password);
		logger.debug("userEmail=================>"+userEmail);
		logger.debug("birth======================>"+_birth);
		logger.debug("userPhone=================>"+userPhone);
		logger.debug("userAddress=================>"+userAddress);
		logger.debug("sex=================>"+_sex);
		logger.debug("questionId=================>"+_questionId);
		logger.debug("answer=================>"+answer);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date birth = null;
		try {
			birth = sdf.parse(_birth);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Integer sex = 0;
		Integer questionId = 0;
		if(_sex != null){
			sex = Integer.parseInt(_sex);
		}
		if(_questionId != null){
			questionId = Integer.parseInt(_questionId);
		}
		Random random = new Random();
		String userCode="";
		for (int i=0;i<6;i++)
		{
			userCode+=random.nextInt(10);
		}
		System.out.println(userCode);
		if(userService.addAnswer(questionId, answer, new Date(),userCode)){
			Safe_question sq = userService.getQ_id(userCode);
			logger.debug("s_id===============>"+sq.getId());
			if(userService.addUser(userCode, userName, password, new Date(), userEmail, sq.getId(), userPhone, userAddress, birth, sex)){
				Trip_user user = userService.getUser(userCode, password);
				session.setAttribute(Constants.USER_SESSION, user);
				return "user/registersuccess";
			}
		}
		model.addAttribute("error","注册失败!!");
		return "user/register";
	}
	
	@RequestMapping(value="dologinjudge")
	public String doLoginJudge(Model model,HttpSession session){
		Trip_user user = (Trip_user) session.getAttribute(Constants.USER_SESSION);
		if(user != null){
			return "redirect:/index/index.do";
		}else{
			model.addAttribute("error","请先登录！");
			return "user/login";
		}
	}
	
	@RequestMapping(value="reset")
	public String reset(Model model){
		List<Trip_question> questions = userService.getAllQuestions();
		model.addAttribute("question",questions);
		return "user/reset";
	}
	
	@RequestMapping(value="getThisQuestion")
	@ResponseBody
	public Trip_question getThisQuestion(@RequestParam("userCode")String userCode){
		logger.debug("userCode=================>"+userCode);
		Safe_question sq = userService.getThisQuestion(userCode);
		logger.debug("sq================>"+sq.getQuestionId());
		Trip_question tq = userService.getThisQuestionByQ_id(sq.getQuestionId());
		return tq;
	}
	
	@RequestMapping(value="judgeQuestion")
	public Object judgeQuestion(Model model,@RequestParam("userCode")String userCode,@RequestParam("userEmail")String userEmail,
			@RequestParam("answer")String answer,@RequestParam("questionId")String qid
			,@RequestParam("password")String password){
		logger.debug("userCode===================>"+userCode);
		logger.debug("answer===================>"+answer);
		logger.debug("userEmail===================>"+userEmail);
		logger.debug("qid===================>"+qid);
		logger.debug("password===================>"+password);
		Integer questionId = 0;
		if(qid != null){
			questionId = Integer.parseInt(qid);
		}
		Safe_question sq = userService.judQuestion(questionId, answer);
		if(sq != null){
			if(userService.modifyPwd(password, new Date(), userCode)){
				return "redirect:/user/login";
			}else{
				model.addAttribute("error","修改失败!账号或者密码输入有误!");
				return "user/reset";
			}
		}else{
			model.addAttribute("error","安全问题答案不正确!!!");
			return "user/reset";
		}
	}
	
	@RequestMapping(value="logout")
	public String logout(HttpSession session){
		session.removeAttribute(Constants.USER_SESSION);
		return "redirect:/index/index.do";
	}
	
	@RequestMapping(value="myinfo")
	public String myInfo(HttpSession session,Model model,@RequestParam(value="pageIndex",required=false)String pageIndex){
		Trip_user user = (Trip_user) session.getAttribute(Constants.USER_SESSION);
		logger.debug("userCode===================>"+user.getUserCode());
		List<Trip_bill> bills = null;
		try {
			bills = userService.getAllBills(user.getUserCode(),0,0);
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.addAttribute("bill",bills);
		return "user/person/frame";
	}
	
	/**
	 * 进入订单管理页面 并获取相应信息
	 * @return
	 */
	@RequestMapping(value="orderAll.html")
	public String orderAll(Model model,
					@RequestParam(value="pageIndex",required=false)String pageIndex,HttpSession session){
		Trip_user user = (Trip_user) session.getAttribute(Constants.USER_SESSION);
		logger.debug("userCode====================>"+user.getUserCode());
		logger.debug("pageIndex===================>"+pageIndex);
		Integer u_id = 0;
		Integer proType = 0;
		List<Trip_bill> bills = null;
		//页面容量
		int pageSize = Constants.pageSize;
		//当前页码
		Integer currentPageNo =1;
		
		if(pageIndex != null){
			try{
				currentPageNo = Integer.valueOf(pageIndex);
			}catch (NumberFormatException e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
		//总数量（表）
		int totalCount = 0;
		try {
			totalCount = userService.count(u_id, proType);
		} catch (Exception e) {
			e.printStackTrace();
		}
		//总页数
		PageSupport pages = new PageSupport();
		pages.setCurrentPageNo(currentPageNo);
		pages.setPageSize(pageSize);
		pages.setTotalCount(totalCount);
		int totalPageCount = pages.getTotalPageCount();
		//控制首页和尾页
		if(currentPageNo < 1){
			currentPageNo = 1;
		}else if(currentPageNo > totalPageCount){
			currentPageNo = totalPageCount;
		}
		try {
			bills = userService.getAllBills(user.getUserCode(), currentPageNo, 10);
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.addAttribute("pages",pages);
		model.addAttribute("bill",bills);
		return "user/person/orderAll";
	}
	
	@RequestMapping(value="perinfo")
	public String perInfo(Model model){
		return "user/person/perInfo";
	}
	@RequestMapping(value="modifyinfo")
	public String modify(Model model,@ModelAttribute Trip_user user,HttpSession session){
		logger.debug("user================>"+user.getUserCode());
		
		user.setModifyDate(new Date());
		if(userService.modifyInfo(user)){
			model.addAttribute("password",user.getPassword());
			model.addAttribute("userCode",user.getUserCode());
			session.removeAttribute(Constants.USER_SESSION);
			return "redirect:/user/dologin";
		}
		model.addAttribute("error","修改失败!!!");
		return "user/person/perInfo";
	}
	
	/**
	 * 进入订单管理页面 并获取相应信息
	 * @return
	 */
	@RequestMapping(value="order.html")
	public String order(Model model,@RequestParam(value="u_id")String id,@RequestParam(value="proType")String _proType,
					@RequestParam(value="pageIndex",required=false)String pageIndex,HttpSession session){
		Trip_user user = (Trip_user) session.getAttribute(Constants.USER_SESSION);
		logger.debug("id===================>"+id);
		logger.debug("proType==================>"+_proType);
		logger.debug("userCode====================>"+user.getUserCode());
		Integer u_id = 0;
		Integer proType = 0;
		List<Trip_bill> bills = null;
		if(id != null){
			u_id = Integer.parseInt(id);
		}
		if(_proType != null){
			proType = Integer.parseInt(_proType);
		}
		//页面容量
		int pageSize = Constants.pageSize;
		//当前页码
		Integer currentPageNo =1;
		
		if(pageIndex != null){
			try{
				currentPageNo = Integer.valueOf(pageIndex);
			}catch (NumberFormatException e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
		//总数量（表）
		int totalCount = 0;
		try {
			totalCount = userService.count(u_id, proType);
		} catch (Exception e) {
			e.printStackTrace();
		}
		//总页数
		PageSupport pages = new PageSupport();
		pages.setCurrentPageNo(currentPageNo);
		pages.setPageSize(pageSize);
		pages.setTotalCount(totalCount);
		int totalPageCount = pages.getTotalPageCount();
		//控制首页和尾页
		if(currentPageNo < 1){
			currentPageNo = 1;
		}else if(currentPageNo > totalPageCount){
			currentPageNo = totalPageCount;
		}
		try {
			bills = userService.getBillsById(user.getUserCode(), u_id, proType, currentPageNo, pageSize);
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.addAttribute("u_id",u_id);
		model.addAttribute("pages",pages);
		model.addAttribute("proType",proType);
		model.addAttribute("bill",bills);
		return "user/person/order";
	}
	
	/**
	 * 查看订单详情
	 * @param model
	 * @param bid
	 * @return
	 */
	@RequestMapping(value="orderInfo")
	public String orderHotel(Model model,@RequestParam("b_id")String bid,@RequestParam("proType")String _proType){
		logger.debug("b_id===================>"+bid);
		logger.debug("proType==================>"+_proType);
		Integer b_id = 0;
		Integer proType = 0;
		
		if(bid != null){
			b_id = Integer.parseInt(bid);
		}
		if(_proType != null){
			proType = Integer.parseInt(_proType);
		}
		if(proType == 2){
			logger.debug("orderHotel=============================>");
			Trip_bill bills = null;
			List<Trip_tourist> tourists = null;
			try {
				bills = userService.getHotelBillsBybid(b_id);
				tourists = userService.getTourists(b_id);
			} catch (Exception e) {
				e.printStackTrace();
			}
			for (Trip_tourist trip_tourist : tourists) {
				System.out.println(trip_tourist.getT_Name());
			}
			model.addAttribute("tourist",tourists);
			model.addAttribute("bill",bills);
			return "user/person/orderInfo";
		}else if(proType == 4){
			logger.debug("orderTravel===============================>");
			Trip_bill bills = null;
			List<Trip_tourist> tourists = null;
			try {
				bills = userService.getTravelBillsBybid(b_id);
				tourists = userService.getTourists(b_id);
			} catch (Exception e) {
				e.printStackTrace();
			}
			model.addAttribute("bill",bills);
			model.addAttribute("tourist",tourists);
			return "user/person/orderTravelInfo";
		}else if(proType==1){
			logger.debug("orderTicket===================>");
			Trip_bill bills = null;
			try {
				bills = userService.getTicketInfo(b_id, proType);
			} catch (Exception e) {
				e.printStackTrace();
			}
			model.addAttribute("bill",bills);
			return "user/person/orderTicketInfo";
		}
		return "user/person/error";
	}
	
	@RequestMapping(value="ticket.html")
	public String ticket(Model model,@RequestParam(value="u_id",required=false)String uid,@RequestParam("proType")String _proType,
					@RequestParam(value="pageIndex",required=false) String pageIndex){
		logger.debug("u_id==================>"+uid);
		logger.debug("proType==================>"+_proType);
		Integer u_id = 0;
		Integer proType = 0;
		List<Trip_bill> bills = null;
		if(uid != null){
			u_id = Integer.parseInt(uid);
		}
		if(_proType != null){
			proType = Integer.parseInt(_proType);
		}
		//页面容量
		int pageSize = Constants.pageSize;
		//当前页码
		Integer currentPageNo =1;
		
		if(pageIndex != null){
			try{
				currentPageNo = Integer.valueOf(pageIndex);
			}catch (NumberFormatException e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
		//总数量（表）
		int totalCount = 0;
		try {
			totalCount = userService.count(u_id, proType);
		} catch (Exception e) {
			e.printStackTrace();
		}
		//总页数
		PageSupport pages = new PageSupport();
		pages.setCurrentPageNo(currentPageNo);
		pages.setPageSize(pageSize);
		pages.setTotalCount(totalCount);
		int totalPageCount = pages.getTotalPageCount();
		//控制首页和尾页
		if(currentPageNo < 1){
			currentPageNo = 1;
		}else if(currentPageNo > totalPageCount){
			currentPageNo = totalPageCount;
		}
		try {
			bills = userService.getTicketBills(u_id, proType, currentPageNo, pageSize);
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.addAttribute("proType",proType);
		model.addAttribute("u_id",u_id);
		model.addAttribute("bill",bills);
		model.addAttribute("pages", pages);
		return "user/person/ticket";
	}
	
	@RequestMapping(value="/del")
	@ResponseBody
	public String del(@RequestParam("b_id")String bid){
		String data = "";
		Integer b_id = 0;
		if(bid != null){
			b_id = Integer.parseInt(bid);
		}
		if(userService.delete(b_id)){
			data = "success";
		}else{
			data = "error";
		}
		return JSONArray.toJSONString(data);
	}
	
	@RequestMapping(value="delete")
	public String delete(@RequestParam("b_id")String bid){
		Integer b_id = 0;
		if(bid != null){
			b_id = Integer.parseInt(bid);
		}
		if(userService.delete(b_id)){
			return "redirect:/user/myinfo";
		}
		return "redirect:/user/orderAll.html";
	}
	
	/**
	 * 修改安全设置页面内容
	 * @return
	 */
	@RequestMapping(value="/safety")
	public String safety(){
		return "user/person/safety";
	}
	@RequestMapping(value="/logpassword")
	public String logPassword(){
		return "user/person/password";
		
	}
	@RequestMapping(value="/judge",method=RequestMethod.POST)
	@ResponseBody
	public String judgePwd(@RequestParam("password")String password,@RequestParam("userCode")String userCode){
		logger.debug("password===================>"+password);
		logger.debug("userCode===================>"+userCode);
		String data = "";
		Trip_user user = userService.judgePwd(userCode, password);
		if(user != null){
			data = "success";
		}else{
			data = "error";
		}
		System.out.println(data);
		return JSONArray.toJSONString(data);
	}
	@RequestMapping(value="/password")
	public String password(HttpSession session,Model model,@RequestParam("newPassword")String password){
		Trip_user user = (Trip_user) session.getAttribute(Constants.USER_SESSION);
		if(userService.modifyPaw(password, user.getUserCode())){
			System.out.println("修改成功！");
			session.removeAttribute(Constants.USER_SESSION);
			return "redirect:/user/login";
		}
		model.addAttribute("error","修改失败!请认真检查填写的内容!");
		return "user/person/password";
	}
	
	@RequestMapping(value="/question.html")
	public String question(Model model,HttpSession session){
		Trip_user _user = (Trip_user) session.getAttribute(Constants.USER_SESSION);
		logger.debug("s_id=================>"+_user.getS_id());
		List<Trip_question> questions = null;
		Trip_user user = null;
		try {
			user = userService.getQuestionBySid(_user.getS_id());
			questions = userService.getAllQuestions();
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.addAttribute("question",questions);
		model.addAttribute("user",user);
		return "user/person/question";
	}
	
	@RequestMapping(value="/judgequestion")
	@ResponseBody
	public String judgeQuestion(@RequestParam("answer")String answer,HttpSession session){
		String data = "";
		Trip_user user = (Trip_user) session.getAttribute(Constants.USER_SESSION);
		logger.debug("s_id====================>"+user.getS_id());
		Safe_question sq =  userService.judgeQuestion(user.getS_id());
		logger.debug("answer=====================>"+sq.getAnswer());
		if(answer.equals(sq.getAnswer()) || answer == sq.getAnswer()){
			data = "success";
		}else{
			data = "error";
		}
		
		return JSONArray.toJSONString(data);
	}
	
	@RequestMapping(value="/savequestion")
	public String saveQuestion(Model model,HttpSession session,@RequestParam("questionId")String qid,@RequestParam("newanswer")String answer){
		Trip_user user = (Trip_user) session.getAttribute(Constants.USER_SESSION);
		logger.debug("s_id====================>"+user.getS_id());
		logger.debug("answer===================>"+answer);
		Integer q_id = 0;
		if(qid != null){
			q_id = Integer.parseInt(qid);
		}
		if(userService.modifyQuestion(q_id, new Date(), user.getS_id(),answer)){
			return "redirect:/user/safety";
		}
		model.addAttribute("error","修改失败!");
		return "user/person/question";
	}
	
	@RequestMapping(value="payment")
	public String pay(@RequestParam(value="b_id",required=false)String bid,@RequestParam(value="isPay",required=false)String _isPay,
						@RequestParam(value="protype",required=false)String _proType,Model model){
		logger.debug("b_id===================>"+bid);
		logger.debug("isPay===================>"+_isPay);
		logger.debug("proType======================>"+_proType);
		Integer b_id = 0;
		Integer isPay = 0;
		Integer proType = 0;
		if(_proType != null){
			proType = Integer.parseInt(_proType);
		}
		if(bid != null){
			b_id = Integer.parseInt(bid);
		}
		if(_isPay!= null){
			isPay = Integer.parseInt(_isPay);
		}
		if(userService.modifyIspay(b_id, isPay)){
			Trip_bill bill = userService.getHotelBillsBybid(b_id);
			logger.debug("totalPrice===================>"+bill.getTotalPrice());
			model.addAttribute("totalPrice",bill.getTotalPrice());
			model.addAttribute("contact",bill.getContact());
			model.addAttribute("phone",bill.getPhone());
			model.addAttribute("roomName",bill.getRoomName());
			model.addAttribute("usingDate",bill.getUsingDate());
			return "index/success";
		}
		model.addAttribute("proType",proType);
		return "index/success";
	}
	
}
